package com.my.socket.nio.v30;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * Created by ZhongGang
 * at 2018/8/21 10:39
 */
public class Writer implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Writer.class);

    private Selector selector;
    private SocketChannel socketChannel;
    private String request;

    Writer(Selector selector, SocketChannel socketChannel, String request) {
        this.selector = selector;
        this.socketChannel = socketChannel;
        this.request = request;
    }

    @Override
    public void run() {
        try {
            String response = this.request.toUpperCase();
            ByteBuffer buffer = ByteBuffer.wrap(response.getBytes());
            this.socketChannel.write(buffer);
            LOGGER.info("write: {}", response);

            this.socketChannel.close();
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
        }
    }
}
